package main

import (
	"backEnd/config"
	"backEnd/database"
	"backEnd/handlers"
	"backEnd/middleware"
	"log"

	"github.com/gin-gonic/gin"
)

func main() {
	// 加载配置
	cfg := config.LoadConfig()

	// 初始化数据库
	if err := database.InitDB(); err != nil {
		log.Fatalf("Failed to initialize database: %v", err)
	}
	defer database.CloseDB()

	// 创建Gin路由
	r := gin.Default()

	// 添加CORS中间件（如果需要）
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With, access-key")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// API路由组
	api := r.Group("/api/bizhi")
	{
		// 所有接口都需要access-key验证
		api.Use(middleware.AuthMiddleware())

		// 首页海报列表
		api.GET("/homeBanner", handlers.GetHomeBanner)

		// 壁纸大分类
		api.GET("/classify", handlers.GetClassify)

		// 分类中壁纸列表
		api.GET("/wallList", handlers.GetWallList)

		// 随机9张壁纸
		api.GET("/randomWall", handlers.GetRandomWall)

		// 单个壁纸详情
		api.GET("/detailWall", handlers.GetDetailWall)

		// 为壁纸评分
		api.GET("/setupScore", handlers.SetupScore)

		// 壁纸下载
		api.GET("/downloadWall", handlers.DownloadWall)

		// 我的评分/下载列表
		api.GET("/userWallList", handlers.GetUserWallList)

		// 用户个人信息
		api.GET("/userInfo", handlers.GetUserInfo)

		// 壁纸资讯公告列表
		api.GET("/wallNewsList", handlers.GetWallNewsList)

		// 壁纸资讯公告详情
		api.GET("/wallNewsDetail", handlers.GetWallNewsDetail)

		// 搜索壁纸
		api.GET("/searchWall", handlers.SearchWall)

		// 近期更新的壁纸列表
		api.GET("/uptodate", handlers.GetUpToDate)

		// 推荐专题列表
		api.GET("/subjectList", handlers.GetSubjectList)

		// 推荐专题详情
		api.GET("/subjectDetail", handlers.GetSubjectDetail)
	}

	// 启动服务器
	addr := cfg.Server.Host + ":" + cfg.Server.Port
	log.Printf("Server starting on %s", addr)
	if err := r.Run(addr); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}
